package com.caiheng.api.controller.platform;

import com.caiheng.api.util.WxUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description
 * @Author
 * @Data 2022/7/22 9:52
 **/
@Component
@RestController
@RequestMapping("/wx/message")
public class WxMessageController extends BaseController {
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${web.message_token}")
    private String message_token;//图片地址

    /**
     * @description 接收消息
     * @author
     * @date 2022/7/22 9:53
     **/
    @RequestMapping(value="/receive",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public void detail(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (WxUtils.checkSignature(signature, timestamp, nonce, message_token)) {
                out.print(echostr);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}
